var app = getApp();
var core = app.requirejs('core');
const api = require("../../utils/api.js")
const authScope = require("../../utils/auth.js")
var image_url = 'https://totolestorage.blob.core.chinacloudapi.cn/totoleec/xcx/giftbag'
Page({
  data: {
    giftbagList: Array,
    giftbagListId: String,
    flang: false,
    isLogin: Boolean,
    mobile: String,
    img_url: {
      structions_rule: image_url + '/rule.png',
      structions_button: image_url + '/button.png',
      structions_button1: image_url + '/button-1.png',
      structions_popup: image_url + '/popup.png',
      structions_check: image_url + '/check.png',
      structions_checked: image_url + '/checked.png',
      structions_textyinsi: image_url + '/text-yinsi.png',
    },
    ico_bl: [],
    pk_kwd: String,
    buttonflnag: false
  },

  // 生命周期函数--监听页面加载
  onLoad: function () {
    let isLogin = app.checkAuth();
    let pages = getCurrentPages()
    let options = pages.pop().options
    this.setData({
      giftbagListId: options.giftbagListId,
      pk_kwd: options.pk_kwd,
      isLogin
    })
    this.selectGiftbagListChange()
    //查询用户是否有礼包
    if (app.getCache('mobileadd') && this.data.isLogin) {
      for (let i = 1; i < 4; i++) {
        this.situationChange(i)
      }
    }
  },
  //监听页面显示
  onShow: function () {
    wx.hideHomeButton();
  },
  //获取登录授权
  bindgetuserinfo() {
    let $this = this
    authScope.scopeLogin().then((res) => {
      if (res) {
        let isLogin = app.checkAuth();
        $this.setData({
          isLogin,
          flang: true
        })
      }
    })
  },
  //活动规则事件
  bottomechnaeg() {
    this.setData({
      buttonflnag: !this.data.buttonflnag
    })
  },
  //隐私跳转
  ysichaneg() {
    wx.navigateTo({
      url: '/pages/custom/index?pageid=102260',
    })
  },
  //领取礼包事件
  receivechaneg() {
    if (this.data.buttonflnag && this.data.isLogin) {
      this.setData({
        flang: true
      })
    }
  },
  //取消弹框
  cancelchaneg() {
   
    this.setData({
      flang: false
    })
  },
  //获取所有礼包
  selectGiftbagListChange() {
    let $this = this;
    let apicontent = api.Limit.selectGiftbagList()
    core.post(apicontent, {}, function (res) {
      $this.setData({
        giftbagList: res.result.map(asd => {
          return asd.id
        })
      })
      let ids = $this.data.giftbagList.indexOf($this.data.giftbagListId);
      if (ids == -1) {
        wx.showModal({
          title: '提示',
          content: '礼包已领完',
          showCancel:false,
          success (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/index/index'
              })
            }
          }
        })
      }
    })
  },
  //获取手机号权限
  getPhoneNumber(e) {
    let $this = this;
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      return;
    }
    if(!app.getCache('userInfo').globalid){
      wx.showModal({
        content: '获取信息失败，请重新获取',
        success (res) {
          if (res.confirm) {
            wx.clearStorage()
            let isLogin = app.checkAuth();
            $this.setData({
              isLogin,
              flang: false
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    }
    // 检查登录态是否过期
    wx.checkSession({
      success(res) {
        wx.login({
          success: res => {
            let data = {
              code: res.code,
              iv: e.detail.iv,
              encryptedData: e.detail.encryptedData
            }
            $this.memberPhone(data)
          }
        })
      },
      fail(err) {
        // session_key 已经失效，需要重新执行登录流程
        wx.login({
          success: res => {
            let data = {
              code: res.code,
              iv: e.detail.iv,
              encryptedData: e.detail.encryptedData
            }
            $this.memberPhone(data)
          }
        })
        wx.showToast({
          title: '获取手机号失败,请重试',
          icon: "none"
        })
      }
    })
  },
  //获取手机号接口
  memberPhone(data) {
    let $this = this
    let apicontent = api.members.memberPhone()
    core.post(apicontent, {
      ...data
    }, function (phone_res) {
      if (phone_res.code == 1) {
        $this.setData({
          mobile: phone_res.data
        })
        app.setCache('mobileadd', phone_res.data);
        let apicontent = api.Limit.receiveGiftLog()
        //记录用户聚到来源
        $this.updateChannelByMemberId()
        //记录用户领取记录
        core.post(apicontent, {
          giftId: $this.data.giftbagListId,
          globalId: app.getCache('userInfo').globalid
        }, function (res) {
          wx.redirectTo({
            url: './giftbag1/giftbag1',
            success: () => {
              wx.showToast({
                title: res.message,
                icon: 'none',
                duration: 2000
              })
            }
          })
        })
      } else {
        wx.showToast({
          title: '获取手机号失败,请重试',
          icon: "none"
        })
      }
    })
  },
  //当前用户优惠卷使用情况请求
  situationChange(status) {
    let $this = this
    let apicontent = api.Limit.selectMemberGiftDetail()
    core.post(apicontent, {
      globalId: app.getCache('userInfo').globalid,
      status: status,
    }, function (res) {
      if (res.result.length != 0) {
        $this.data.ico_bl.push(true)
      } else {
        $this.data.ico_bl.push(false)
      }
      if (status == 3) {
        let asd = $this.data.ico_bl.indexOf(true)
        if (asd != -1) {
          $this.setData({
            buttonflnag: true
          })
          wx.redirectTo({
            url: './giftbag1/giftbag1'
          })
        }
      }
    })
  },
  //记录用户来源聚到
  updateChannelByMemberId() {
    let $this = this;
    let apicontent = api.Limit.updateChannelByMemberId()
    core.post(apicontent, {
      memberId: app.getCache('userinfo_id'),
      channel: $this.data.pk_kwd
    }, function (res) {
      console.log(res);
    })
  },
  navigate: function (e) {
    var phone = e.currentTarget.dataset.phone
    var appid = e.currentTarget.dataset.appid
    var appurl = e.currentTarget.dataset.appurl
    var url = e.currentTarget.dataset.url

    if (url.includes('?cate')) {
      let params = url.split('?')
      if (params[1].includes('cate')) {
        let cateid = params[1].split('=')[1]

        app.setCache("cateid", cateid)
      }
      wx.switchTab({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: function () {
          wx.switchTab({
            url: url,
          })
        }
      })
    }
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      })
    }
    if (appid) {
      wx.navigateToMiniProgram({
        appId: appid,
        path: appurl
      })
    }
  },
})